# $Id$

"""
history.py
----------

Generates a historical view of raids

"""

from django.template import Context, loader
from django.http import HttpResponse, Http404 
from monulu.raid.models import  Character
from monulu.sk.models import SKList, SKSuicide

from RaidResult import RaidResult
from RaidRank import RaidRank

def history(request, list_id, raid_id=0):
    skl = SKList.objects.get(pk=list_id)
    if not raid_id:
        raid_id = skl.getLastRaid().pk
    hraids = [RaidResult(raid) for raid in skl.getRaids()]
    if not raid_id in hraids:
        raise Http404
    # slicing raids at the specified point    
    i = hraids.index(raid_id)
    hraids = hraids[:i+1]
    
    for hraid in hraids:
        hraid.ranks = skl.getRanks(hraid.getId())
        hraid.suicides = SKSuicide.objects.filter(raid=hraid.getId(),is_suicide=1).order_by('skorder')
        hraid.greeds = SKSuicide.objects.filter(raid=hraid.getId(),is_suicide=0).order_by('skorder')

    # The ranks arrays will always be the same length as they are each 
    # derived from SKStart
    rt=[[] for h in hraids[0].ranks]

    for i in range (0, len(hraids[0].ranks)):
        for hraid in hraids:
            char = Character.objects.get(pk=hraid.ranks[i][0])
            rt[i].extend([RaidRank(hraid.ranks[i][0], 
                          char,
                          hraid.ranks[i][1], 
                          hraid.raid.isInRaid(char),
                          SKSuicide.objects.filter(raid=hraid.raid,character=char))])

    t = loader.get_template('sk/history.html')
    c = Context({'hraids':hraids,'rt': rt,})
    return HttpResponse(t.render(c))
